package com.bjpowernode.pmes.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bjpowernode.pmes.bean.AuthHistory;
import com.bjpowernode.pmes.bean.BugTicket;
import com.bjpowernode.pmes.bean.BugTickets;
import com.bjpowernode.pmes.bean.Page;
import com.bjpowernode.pmes.bean.Result;
import com.bjpowernode.pmes.bean.User;
import com.bjpowernode.pmes.common.BaseController;
import com.bjpowernode.pmes.service.BugTicketService;
import com.bjpowernode.pmes.util.Const;
import com.bjpowernode.pmes.util.DateUtil;

@Controller
@RequestMapping("/bt")
public class BugTicketController extends BaseController {

	@Resource
	private BugTicketService bugTicketService;
	@Resource
	private RepositoryService repositoryService;
	@Resource
	private RuntimeService runtimeService;
	@Resource
	private TaskService taskService;
	@Resource
	private HistoryService historyService;
	
	/**
	 * 审批故障单信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/doAuth")
	public Object doAuth( String piid, String taskid, BugTicket bt, AuthHistory ah, HttpSession session ) throws Exception {
		
		Result r = new Result();
		
		try {
			
			// 增加审批历史记录
			ah.setOpertype("同意");
			ah.setAuthtime(DateUtil.getSystemtime());
			
			User loginUser = (User)session.getAttribute(Const.SESS_P_USER);
			ah.setUserid(loginUser.getId());
			bugTicketService.insertAuthHistory(ah);
			
			// 完成任务
			taskService.complete(taskid);

			HistoricProcessInstance hpi =
				historyService
					.createHistoricProcessInstanceQuery()
					.processInstanceId(piid)
					.finished()
					.singleResult();
			
			if ( hpi != null ) {
				// 更新故障单的状态
				bt.setStatus("2");
				bt.setId(ah.getBtid());
				bugTicketService.updateBtAuthStatus(bt);
			}
			
			r.setSuccess(true);
		} catch ( Exception e ) {
			e.printStackTrace();
			r.setSuccess(false);
		}
		
		return r;
	}
	
	/**
	 * 故障单派障功能
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/doAssign")
	public Object doAssign( BugTicket bt ) throws Exception {
		Result r = new Result();

		try {
//			// 查询故障单审批流程定义
//			ProcessDefinition pd =
//				repositoryService
//				    .createProcessDefinitionQuery()
//				    .processDefinitionKey("bugflow")
//				    .latestVersion()
//				    .singleResult();
//			
//			// 启动流程
//			ProcessInstance pi = runtimeService.startProcessInstanceById(pd.getId());
//			
			// 修改故障单的状态
			bt.setStatus("1");
			
			bugTicketService.updateBtStatus(bt);
			
			r.setSuccess(true);
		} catch ( Exception e ) {
			e.printStackTrace();
			r.setSuccess(false);
		}
		
		return r;
	}
	
	/**
	 * 删除选择的故障单信息
	 * @param bts
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/deleteBts")
	public Object deleteBts( BugTickets bts ) throws Exception {
		
		Result r = new Result();

		try {
			
			bugTicketService.deleteBts(bts);
			r.setSuccess(true);
		} catch ( Exception e ) {
			e.printStackTrace();
			r.setSuccess(false);
		}
		
		return r;
	}
	
	/**
	 * 修改故障单信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Object update( BugTicket bt ) throws Exception {
		
		Result r = new Result();
		
		try {
			bugTicketService.updateBt(bt);
			r.setSuccess(true);
		} catch ( Exception e ) {
			e.printStackTrace();
			r.setSuccess(false);
		}
		
		return r;
	}
	
	/**
	 * 查询故障单的审批历史信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/queryHistory")
	public Object queryHistory( BugTicket bt ) throws Exception {
		
		List<AuthHistory> historyList = bugTicketService.getBtHistorys(bt);
		Integer cnt = bugTicketService.getBtHistoryCnt(bt);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		resultMap.put("total", cnt);
		resultMap.put("rows", historyList);
		
		return resultMap;
	}
	
	/**
	 * 分页查询归档故障单信息
	 * @param pageno
	 * @param pagesize
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/pageQueryFinished")
	public Object pageQueryFinished(@RequestParam("page")Integer pageno, @RequestParam("rows")Integer pagesize) throws Exception {
		
		Page<BugTicket> btPage = bugTicketService.getPageByFinished(pageno, pagesize);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		resultMap.put("total", btPage.getTotalsize());
		resultMap.put("rows", btPage.getDataList());
		
		return resultMap;
	}
	
	/**
	 * 分页查询已审故障单信息
	 * @param pageno
	 * @param pagesize
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/pageQueryAuthed")
	public Object pageQueryAuthed(@RequestParam("page")Integer pageno, @RequestParam("rows")Integer pagesize, HttpSession session) throws Exception {
		
		User loginUser = (User)session.getAttribute(Const.SESS_P_USER);
		
		Page<BugTicket> btPage = bugTicketService.getPageByAuthed(loginUser, pageno, pagesize);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		resultMap.put("total", btPage.getTotalsize());
		resultMap.put("rows", btPage.getDataList());
		
		return resultMap;
	}
	
	/**
	 * 分页查询待审故障单信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/pageQueryAuth")
	public Object pageQueryAuth(@RequestParam("page")Integer pageno, @RequestParam("rows")Integer pagesize, HttpSession session) throws Exception {
		
		User loginUser = (User)session.getAttribute(Const.SESS_P_USER);
		
		// 查询当前用户的任务
		TaskQuery query = taskService.createTaskQuery();
		
		query = query.taskAssignee(loginUser.getLoginacct());
		
		List<Task> taskList = query.listPage((pageno-1)*pagesize, pagesize);
		List<Map<String, Object>> taskMapList = new ArrayList<Map<String, Object>>();
		for ( Task t : taskList ) {
			Map<String, Object> taskMap = new HashMap<String, Object>();
			
			// 根据任务查找流程实例
			String piid = t.getProcessInstanceId();
			
			// 根据任务查找故障单。
			BugTicket bt = bugTicketService.getBtByPI(piid);
			
			taskMap.put("id", t.getId());
			taskMap.put("piid", piid);
			taskMap.put("btid", bt.getId());
			taskMap.put("remark", bt.getRemark());
			
			String pdid = t.getProcessDefinitionId();
			
			ProcessDefinition pd =
				repositoryService
				    .createProcessDefinitionQuery()
				    .processDefinitionId(pdid)
				    .singleResult();
			
			taskMap.put("pdname", pd.getName());
			taskMap.put("taskname", t.getName());
			taskMap.put("tasktime", DateUtil.format(t.getCreateTime(), Const.DATE_FORMAT_ALL));
			taskMap.put("username", bt.getUsername());
			taskMap.put("createtime", bt.getCreatetime());
			taskMap.put("happentime", bt.getHappentime());
			taskMap.put("levelLabel", bt.getLevelLabel());
			taskMap.put("addressLabel", bt.getAddressLabel());
			
			taskMapList.add(taskMap);
		}
		
		long cnt = query.count();
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		resultMap.put("total", cnt);
		resultMap.put("rows", taskMapList);
		
		return resultMap;
	}
	
	/**
	 * 分页查询故障单信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/pageQuery")
	public Object pageQuery(@RequestParam("page")Integer pageno, @RequestParam("rows")Integer pagesize, HttpSession session) throws Exception {
		
		User loginUser = (User)session.getAttribute(Const.SESS_P_USER);
		
		Page<BugTicket> page = bugTicketService.getAllBts(loginUser, pageno, pagesize);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		resultMap.put("total", page.getTotalsize());
		resultMap.put("rows", page.getDataList());
		
		return resultMap;
	}
	
	/**
	 * 增加故障单信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/insert")
	public Object insert(BugTicket bt, HttpSession session) throws Exception {
		
		Result r = new Result();
		
		try {
			bt.setCreatetime(DateUtil.getSystemtime());
			bt.setStatus("0");
			User loginUser = (User)session.getAttribute(Const.SESS_P_USER);
			bt.setUserid(loginUser.getId());
			bugTicketService.insertBugTicket(bt);
			r.setSuccess(true);
		} catch ( Exception e ) {
			e.printStackTrace();
			r.setSuccess(false);
		}
		
		return r;
	}
	
	/**
	 * 跳转到故障单的新增页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/add")
	public String add() throws Exception {
		return "bt/add";
	}
	
	/**
	 * 跳转到故障单的归档页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/finished")
	public String finished() throws Exception {
		return "bt/finished";
	}
	
	/**
	 * 跳转到故障单的已审页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/authed")
	public String authed() throws Exception {
		return "bt/authed";
	}
	
	/**
	 * 跳转到故障单的待审页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/auth")
	public String auth() throws Exception {
		return "bt/auth";
	}
	
	/**
	 * 跳转到故障单的分页查询页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/index")
	public String index() throws Exception {
		return "bt/index";
	}
}
